import api from "../../utils/api"
import Utils from "../../utils/utils"

// pages/cart/cart.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [] as CartContentModel[],//购物车列表
    allChoose: false as boolean,//是否全选
    btnDisabled: true as boolean,//立即结算按钮是否可以点击
    totalAmount: '0.00' as string,//总价格
  },
  subNum(e: any): void {
    this.setData({
      btnDisabled: true
    })
    const id = e.currentTarget.dataset.id
    const { cartList } = this.data
    cartList.forEach(item => {
      if (item.count && item.id == id) {
        if (item.count != 1) {
          const count = item.count - 1
          this.changeNum(id, count, () => {
            item.count = count
            this.setData({
              cartList,
              btnDisabled: this.data.totalAmount == '0.00' ? true : false
            })
            this.calcPrice()
          })
        } else {
          api.cart.deleteCartContent({ id }).then(res => {
            if (res.data.code == "000") {
              // 删除了就将cartListid相同项删除
              const deleData = cartList.filter(item => {
                return item.id != id;
              })
              this.setData({
                cartList: deleData
              })
            } else {
              wx.showToast({
                title: res.data.message as string,
                icon: "error"
              })
            }
          })
        }
      }
    })

  },
  addNum(e: any): void {
    this.setData({
      btnDisabled: true
    })
    const id = e.currentTarget.dataset.id
    const { cartList } = this.data
    cartList.forEach(item => {
      if (item.count && item.id == id) {
        const count = item.count + 1
        this.changeNum(id, count, () => {
          item.count = count
          this.setData({
            cartList,
            btnDisabled: this.data.totalAmount == '0.00' ? true : false
          })
          this.calcPrice();
        })
      }
    })
  },
  // 改变某个订单的选中状态
  changeStatus(e: any): void {
    const { cartList } = this.data
    let count = 0
    cartList.map(item => {
      if (item.id == e.currentTarget.dataset.id) {
        item.choose = !item.choose
      }
      if (item.choose) {
        count += 1;
      }
    })
    if (count == cartList.length) {
      this.setData({
        allChoose: true
      })
    } else {
      this.setData({
        allChoose: false
      })
    }
    this.setData({
      cartList
    })
    this.calcPrice();
  },
  // 获取购物车列表
  getCartContents(): void {
    api.cart.getCartContents().then(res => {
      if (res.data.code == "000" && res.data.data) {
        // TODO:根据每个商品的状态展示不同的效果
        // const cartList = res.data.data
        const cartList = res.data.data.filter(item => item.status === 'VALIDATE');
        if (cartList) {
          cartList.forEach(item => {
            item.price = Utils.priceToYuan(item.price as number)
            item.choose = false
          })
          this.setData({
            cartList
          })
        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 改变全部的选中状态
  changeAllStatus(): void {
    const { allChoose, cartList } = this.data
    if (allChoose) {
      cartList.forEach(item => {
        item.choose = false
      })
    } else {
      cartList.forEach(item => {
        item.choose = true
      })
    }
    this.setData({
      allChoose: !allChoose,
      cartList
    })
    this.calcPrice();
  },
  // 修改数量
  async changeNum(id: number, count: number, callback: () => void): Promise<void> {
    const params = {
      id,
      count
    }
    api.cart.modifyCount(params).then(res => {
      if (res.data.code == "000") {
        callback();
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })

  },
  // 计算总价
  calcPrice(): void {
    const { cartList } = this.data
    let totalAmount = 0
    cartList.map(item => {
      if (item.choose) {
        totalAmount += Number(item.price) * item.count!;
      }
    })
    this.setData({
      totalAmount: totalAmount.toFixed(2),
      btnDisabled: totalAmount.toFixed(2) == '0.00' ? true : false
    })
  },
  // 立即结算
  settlement(): void {
    try {
      const { cartList } = this.data
      const orderCommodities = cartList.map(item => {
        if (item.choose) {
          return {
            commodityId: item.commodityId,
            count: item.count,
            cartContentId: item.id
          }
        }
      }).filter(Boolean) as OrderCommodity[]
      const params = {
        autoSelectCoupon: true,
        orderCommodities,
        fromCart: true
      } as PreviewOrderParam
      api.order.previewOrder(params).then(res => {
        if (res.data.code == '000') {
          const previewInfo = JSON.stringify(res.data.data)
          wx.navigateTo({
            url: "/pages/order/order?data=" + encodeURIComponent(previewInfo) + "&fromCart=1"
          })
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: "error"
          })
        }
      })
    } catch (error) {
      console.error("JSON.stringify出错")
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(): void {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      allChoose: false
    })
    this.getCartContents();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})